package com.kdd.campus.sh.service.impl;

import com.github.pagehelper.PageHelper;
import com.kdd.campus.sh.dao.Admin_userMapper;
import com.kdd.campus.sh.dao.FootprintMapper;
import com.kdd.campus.sh.dao.UserMapper;
import com.kdd.campus.sh.dto.LoginUserDto;
import com.kdd.campus.sh.po.Admin_user;
import com.kdd.campus.sh.po.ShFootprint;
import com.kdd.campus.sh.po.User;
import com.kdd.campus.sh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/****
 * @Author:shenkunlin
 * @Description:User业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private Admin_userMapper admin_userMapper;
    @Autowired
    private FootprintMapper footprintMapper;

    /**
     * 根据ID查询User
     * @param id
     * @return
     */
    @Override
    public User findById(Long id){
        return  userMapper.selectByPrimaryKey(id);
    }

    @Override
    public Admin_user findAdminById(Long id) {
        return admin_userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User login(String openid, LoginUserDto userDto) {
        // 根据openid查询用户是否登录过
        User user = userMapper.selectOne(User.builder().openId(openid).build());
        if (user == null){
            // openid不存在，用户第一次登录，看作注册,执行插入操作
            user = User.builder()
                    .openId(openid)
                    .username(userDto.getNickname())
                    .headPortrait(userDto.getAvatarUrl())
                    .gender(userDto.getGender())
                    .phone(userDto.getPhone())
                    .created(new Date())
                    .modified(new Date())
                    .build();
            userMapper.insertSelective(user);
        }else {
            // 登录成功
        }
        return user;
    }

    @Override
    public void update(User user) {
        user.setModified(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void delete(Long userId) {
        userMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }

    @Override
    public List<ShFootprint> getFootprint(Long userId) {
        PageHelper.startPage(0, 30);
        Example example = new Example(ShFootprint.class);
        example.setOrderByClause("created desc");
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("isDelete", false);

        return footprintMapper.selectByExample(example);
    }
}
